/**
 * Created by easy on 15/5/12.
 */
$(document).ready(function () {
    $("#dynamicCount").hide(0);
    pullToRefresh.init({
        loadingFunction: util.pullToRefresh
    });
    vars.type_arr = [];
    vars.type_arr["OrderAdd"] = "增加了一条订单";
    vars.type_arr["OrderClose"] = "关闭了一条订单";
    vars.type_arr["OrderCompleted"] = "完成了订单";
    vars.type_arr["OrderRec"] = "订单接收";
    vars.type_arr["RemarkAdd"] = "增加了订单备注";
    vars.type_arr["RemarkUpd"] = "更新了订单备注";
    vars.type_arr["AbnormalAdd"] = "新增一条异常";
    vars.type_arr["AbnormalClose"] = "完成了异常";
    vars.type_arr["AbnormalReOpen"] = "重新打开异常";
    vars.type_arr["AbnRemarkAdd"] = "增加了异常备注";
    vars.type_arr["AbnRemarkUpd"] = "更新了异常备注";
    vars.type_arr["DocumentAdd"] = "附件上传";
    vars.type_arr["DocumentDel"] = "附件删除";
    vars.type_arr["ProcessCompleteDateDate"] = "更新流程实际完成时间";
    vars.type_arr["ProcessExpirationDate"] = "更新流程预计时间";
    vars.type_arr["ProcessT"] = "完成了流程";
    vars.type_arr["ProcessF"] = "取消完成流程";
    vars.type_arr["ProgressAdd"] = "增加了流程备注";
    vars.type_arr["ProgressUpd"] = "更新了流程备注";
    vars.type_arr["ProgressDel"] = "删除了流程备注";
    vars.type_arr["PictureAdd"] = "示意图上传";
    vars.type_arr["PictureDel"] = "删除示意图";
    var formatDate = function (time) {
        if (typeof time != "number") {
            time = parseInt(time)
        }
        return mc.dealTime(time, "yyyy-MM-dd hh:mm")
    };
    var setName = function (name) {
        return name.split(".")[0]
    };
    var getAjaxID = function (string) {
        if (string != undefined && string != null) {
            return string.split("#")[1]
        } else {
            return "";
        }
    };
    var getAjaxStatus = function (string) {
        if (string != undefined && string != null) {
            return string.split("#")[0]
        } else {
            return "";
        }
    };
    vars.ractiveLocalDynamicList = new Ractive({
        el: "CONTAINER-localdynamic",
        template: "#TEMPLATE-localdynamic",
        data: {ractiveData: [], formatDate: formatDate, setName: setName}
    });
    vars.ractiveAllDynamicList = new Ractive({
        el: "CONTAINER-alldynamic",
        template: "#TEMPLATE-alldynamic",
        data: {ractiveData: [], formatDate: formatDate, setName: setName}
    });
    vars.ractiveAllRemarksList = new Ractive({
        el: "CONTAINER-allRemarks",
        template: "#TEMPLATE-allRemarks",
        data: {
            ractiveData: [],
            formatDate: formatDate,
            setName: setName,
            getAjaxID: getAjaxID,
            getAjaxStatus: getAjaxStatus
        }
    });
    vars.ractiveSystemMessageList = new Ractive({
        el: "CONTAINER-systemMessage",
        template: "#TEMPLATE-systemMessage",
        data: {ractiveData: [], formatDate: formatDate, setName: setName}
    });
});
(function () {
    vars.currentPage = 1;
    vars.pageSize = 10;
    basic.deviceReady = function () {
        if (!vars.userInfo) {
            mc.getUserInfo(function (data) {
                vars.userInfo = JSON.parse(data);
            })
        }
        util.getLocalDynamicData(mc.showContent);
        mc.getDataFromLocalStorage("dynamicItem", function (data) {
            data = data ? JSON.parse(data) : 1;
            util.tabtoswitch(data, $(".tab-btn")[parseInt(data) - 1]);
            //$($(".tab-btn")[parseInt(data) - 1]).addClass("active");
        }, "app");
        service.getProcessUnreadCount(function (dataCount) {
            if (dataCount.count > 0) {
                $("#dynamicCount").text(dataCount.count).show(0);
                mc.getMessageCount("remark", ' ');
            } else {
                $("#dynamicCount").hide(0);
                mc.getMessageCount("remark", '');
            }
        });
        service.getAllHistoryUnreadCount(function (data) {
            if (data) {
                $("#dynamicOld").show();
            }
        })
        document.addEventListener('ViewDidAppear', basic.ViewDidAppear, false);
    };
    basic.ViewDidAppear = function () {
        if (!vars.userInfo) {
            mc.getUserInfo(function (data) {
                vars.userInfo = JSON.parse(data);
            })
        }
        util.getLocalDynamicData(mc.showContent);
        service.getProcessUnreadCount(function (dataCount) {
            if (dataCount.count > 0) {
                $("#dynamicCount").text(dataCount.count).show(0);
                mc.getMessageCount("remark", ' ');
            } else {
                $("#dynamicCount").hide(0);
                mc.getMessageCount("remark", '');
            }
        });
        service.getAllHistoryUnreadCount(function (data) {
            if (data) {
                $("#dynamicOld").show();
            }
        });
        mc.getDataFromLocalStorage("dynamicItem", function (data) {
            data = data ? JSON.parse(data) : 1;
            util.tabtoswitch(data, $(".tab-btn")[parseInt(data) - 1]);
            //$($(".tab-btn")[parseInt(data) - 1]).addClass("active");
        }, "app");
    };
    basic.rightButtonEvent = function () {
        mc.uploadAllAjaxTask(function (data) {
        })
    };
    util.syncDynamicsData = function (callback) {
        mc.syncData(["QC_REMARK", "QC_DYNAMIC"], function () {
            callback()
        })
    };
    util.syncMessageData = function (callback) {
        mc.syncData(["QC_REMARK", "QC_MESSAGE"], function () {
            callback()
        })
    };
    util.syncRemarksData = function (callback) {
        mc.syncData(["QC_REMARK", "QC_ORDER", "QC_PROCESS"], function () {
            callback()
        })
    };
    util.addProcessRemarkReply = function (remarkID, processName) {
        mc.jump('submit.html?submitType=8&type=3&objID=' + remarkID + '&pID=' + remarkID + '&processName=' + processName, '新增备注回复', 'SubmitModal');
    };
    util.replyRemark = function (parentRemarkID, toUserID, toUserName, processName) {
        if (toUserID) {
            mc.jump('submit.html?submitType=8&type=3&objID=' + parentRemarkID + '&processName=' + processName + "&toUserID=" + toUserID + "&toUserName=" + toUserName, '回复 ' + toUserName, 'SubmitModal');
        } else {
            mc.jump('submit.html?submitType=8&type=3&objID=' + parentRemarkID + '&processName=' + processName, '回复异常', 'SubmitModal');
        }
    };
    util.tabtoswitch = function (item, touchObj) {
        mc.saveDataToLocalStorage("dynamicItem", item, function () {

        }, "app");
        $(".mc-nodata").hide();
        $(touchObj).addClass("active").siblings(".tab-btn").removeClass("active");
        switch (item) {
            case 1:
                util.getLocalDynamicData();
                $(".local-view").removeClass("no-display").siblings(".dynamic-view").addClass("no-display");
                break;
            case 2:
                util.getRemarksData(function () {
                    util.syncRemarksData(util.getRemarksData);
                    service.getProcessUnreadCount(function (dataCount) {
                        if (dataCount.count > 0) {
                            $("#dynamicCount").text(dataCount.count).show(0);
                            mc.getMessageCount("remark", ' ');
                        } else {
                            $("#dynamicCount").hide(0);
                            mc.getMessageCount("remark", '');
                        }
                    });
                    service.getAllHistoryUnreadCount(function (data) {
                        if (data) {
                            $("#dynamicOld").show();
                        }
                    });
                });
                $("#CONTAINER-allRemarks").removeClass("no-display").siblings(".dynamic-view").addClass("no-display");
                break;
            case 3:
                util.getDynamicData(2, function () {
                    util.syncDynamicsData(function () {
                        util.getDynamicData(2);
                    });
                });
                $("#CONTAINER-alldynamic").removeClass("no-display").siblings(".dynamic-view").addClass("no-display");
                break;
            case 4:
                util.getMessageData(function () {
                    util.syncMessageData(function () {
                        util.getMessageData();
                    });
                });
                $("#CONTAINER-systemMessage").removeClass("no-display").siblings(".dynamic-view").addClass("no-display");
                break;
        }
    };
    util.getLocalDynamicData = function (callback) {
        var getLocalDynamicDataCallback = function (data) {
            //alert(JSON.stringify(data))
            vars.ractiveLocalDynamicList.data.ractiveData = data;
            vars.ractiveLocalDynamicList.update("ractiveData");
            common.changePhotosProgress();
            //common.showPhotos(data);
            if (callback != undefined) {
                callback()
            }
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfLocalDynamicList
            };
            common.morePage(optionsForMorePage);
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getAjaxData(options, getLocalDynamicDataCallback)
    };
    util.paginationOfLocalDynamicList = function () {
        var paginationOfLocalDynamicListCallback = function (data) {
            vars.ractiveLocalDynamicList.data.ractiveData = $.merge(vars.ractiveLocalDynamicList.data.ractiveData, data);
            vars.ractiveLocalDynamicList.update("ractiveData");
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfLocalDynamicList
            };
            common.morePage(optionsForMorePage);
        };
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getAjaxData(options, paginationOfLocalDynamicListCallback)
    };

    util.getDynamicData = function (type, callback) {
        var getDynamicDataCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i in data) {
                data[i].type = vars.type_arr[data[i].type];
                //data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "null" ? [JSON.parse(data[i].orderAttachment)[0]] : [];
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "undefined" && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            vars.ractiveAllDynamicList.data.ractiveData = data;
            vars.ractiveAllDynamicList.update("ractiveData");
            //alert(JSON.stringify(data))
            common.showFirstOrderPhotos(data);
            common.showPhotos(data);
            if (callback != undefined) {
                callback()
            }
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfDynamicList
            };
            common.morePage(optionsForMorePage);
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize,
            type: type
        };
        service.getDynamicData(options, getDynamicDataCallback);
        service.updateHistoryUnreadMark(function () {
            $("#dynamicOld").hide();
        });
    };

    util.paginationOfDynamicList = function () {
        var paginationOfDynamicListCallback = function (data) {
            for (var i in data) {
                data[i].type = vars.type_arr[data[i].type];
                //data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "null" ? [JSON.parse(data[i].orderAttachment)[0]] : [];
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "undefined" && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            vars.ractiveAllDynamicList.data.ractiveData = $.merge(vars.ractiveAllDynamicList.data.ractiveData, data);
            vars.ractiveAllDynamicList.update("ractiveData");
            common.showFirstOrderPhotos(data, vars.currentPage);
            common.showPhotos(data);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfDynamicList
            };
            common.morePage(optionsForMorePage);
        };
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getDynamicData(options, paginationOfDynamicListCallback)
    };

    util.getMessageData = function (callback) {
        var getMessageDataCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i in data) {
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            vars.ractiveSystemMessageList.data.ractiveData = data;
            vars.ractiveSystemMessageList.update("ractiveData");
            common.showFirstOrderPhotos(data);
            if (callback != undefined) {
                callback()
            }
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfMessageList
            };
            common.morePage(optionsForMorePage);
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getMessageData(options, getMessageDataCallback);
    };

    util.paginationOfMessageList = function () {
        var paginationOfMessageListCallback = function (data) {
            for (var i in data) {
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            vars.ractiveSystemMessageList.data.ractiveData = $.merge(vars.ractiveAllDynamicList.data.ractiveData, data);
            vars.ractiveSystemMessageList.update("ractiveData");
            common.showFirstOrderPhotos(data, vars.currentPage);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfMessageList
            };
            common.morePage(optionsForMorePage);
        };
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getMessageData(options, paginationOfMessageListCallback)
    };

    util.getRemarksData = function (callback) {
        var getRemarksDataCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i in data) {
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            var datas = vars.ractiveAllRemarksList.data.ractiveData = data;
            vars.ractiveAllRemarksList.update("ractiveData");
            var jsonPKStr = "";
            for (var i = 0; i < datas.length; i++) {
                jsonPKStr += ("'" + datas[i].jsonPK + "'");
                if (i != datas.length - 1) {
                    jsonPKStr += ",";
                }
            }
            service.updateProcessUnreadMark(jsonPKStr, function () {
                /*service.getProcessUnreadCount(function (dataCount) {
                 if(dataCount.count>0) {
                 $("#dynamicCount").text(dataCount.count).show(0);
                 mc.getMessageCount("remark", ' ');
                 }else{
                 mc.getMessageCount("remark", '');
                 }
                 });*/
            });
            common.showPhotos(data);
            common.showFirstOrderPhotos(data);
            common.changePhotosProgress();
            if (callback != undefined) {
                callback()
            }
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfRemarksList
            };
            common.morePage(optionsForMorePage);
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessRemarkData(options, getRemarksDataCallback);
    };

    util.paginationOfRemarksList = function () {
        var paginationOfRemarksListCallback = function (data) {
            for (var i in data) {
                data[i].orderAttachment = data[i].orderAttachment != undefined && data[i].orderAttachment != null && data[i].orderAttachment != "null" ? JSON.parse(data[i].orderAttachment)[0] : null;
            }
            var datas = vars.ractiveAllRemarksList.data.ractiveData = $.merge(vars.ractiveAllRemarksList.data.ractiveData, data);
            vars.ractiveAllRemarksList.update("ractiveData");

            var jsonPKStr = "";
            for (var i = 0; i < datas.length; i++) {
                jsonPKStr += ("'" + datas[i].jsonPK + "'");
                if (i != datas.length - 1) {
                    jsonPKStr += ",";
                }
            }
            service.updateProcessUnreadMark(jsonPKStr, function () {
                service.getProcessUnreadCount(function (dataCount) {
                    if (dataCount.count > 0) {
                        $("#dynamicCount").text(dataCount.count).show(0);
                        mc.getMessageCount("remark", ' ');
                    } else {
                        mc.getMessageCount("remark", '');
                    }
                    common.showPhotos(data);
                    common.showFirstOrderPhotos(data, vars.currentPage);
                    var optionsForMorePage = {
                        mode: "normal",
                        dataLength: data.length,
                        scrollContainer: $("#content"),
                        callback: util.paginationOfRemarksList
                    };
                    common.morePage(optionsForMorePage);
                });
            })
        };
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessRemarkData(options, paginationOfRemarksListCallback)
    };

    util.pullToRefresh = function () {
        //util.getLocalDynamicData(pullToRefresh.reset);
        var view = parseInt($(".tab-btn.active").attr("value"));
        switch (view) {
            case 1:
                util.getLocalDynamicData(pullToRefresh.reset);
                mc.syncData(["QC_REMARK", "QC_MESSAGE"], function () {
                    service.getProcessUnreadCount(function (dataCount) {
                        if (dataCount.count > 0) {
                            $("#dynamicCount").text(dataCount.count).show(0);
                            mc.getMessageCount("remark", ' ');
                        } else {
                            $("#dynamicCount").hide(0);
                            mc.getMessageCount("remark", '');
                        }
                    });
                    service.getAllHistoryUnreadCount(function (data) {
                        if (data) {
                            $("#dynamicOld").show();
                        }
                    });
                });
                break;
            case 2:
                util.syncRemarksData(function () {
                    util.getRemarksData(pullToRefresh.reset);
                    service.getProcessUnreadCount(function (dataCount) {
                        if (dataCount.count > 0) {
                            $("#dynamicCount").text(dataCount.count).show(0);
                            mc.getMessageCount("remark", ' ');
                        } else {
                            $("#dynamicCount").hide(0);
                            mc.getMessageCount("remark", '');
                        }
                    });
                    service.getAllHistoryUnreadCount(function (data) {
                        if (data) {
                            $("#dynamicOld").show();
                        }
                    });
                });
                break;
            case 3:
                util.syncDynamicsData(function () {
                    util.getDynamicData(2, pullToRefresh.reset);
                    service.getProcessUnreadCount(function (dataCount) {
                        if (dataCount.count > 0) {
                            $("#dynamicCount").text(dataCount.count).show(0);
                            mc.getMessageCount("remark", ' ');
                        } else {
                            $("#dynamicCount").hide(0);
                            mc.getMessageCount("remark", '');
                        }
                    });
                    service.getAllHistoryUnreadCount(function (data) {
                        if (data) {
                            $("#dynamicOld").show();
                        }
                    });
                });
                break;
            case 4:
                util.syncMessageData(function () {
                    util.getMessageData(pullToRefresh.reset);
                    service.getProcessUnreadCount(function (dataCount) {
                        if (dataCount.count > 0) {
                            $("#dynamicCount").text(dataCount.count).show(0);
                            mc.getMessageCount("remark", ' ');
                        } else {
                            $("#dynamicCount").hide(0);
                            mc.getMessageCount("remark", '');
                        }
                    });
                    service.getAllHistoryUnreadCount(function (data) {
                        if (data) {
                            $("#dynamicOld").show();
                        }
                    });
                });
                break;
        }
    };
    util.showLocalPhotosByIndex = function (jsonPK, currIndex) {
        var data = vars.ractiveLocalDynamicList.data.ractiveData;
        var photoKeyArray = [];
        for (var i = 0; i < data.length; i++) {
            if (data[i].FCloudDataTransferID == jsonPK) {
                var photosData = JSON.parse(data[i].FCloudDataTransferExtra).photos;
                for (var j = 0; j < photosData.length; j++) {
                    photoKeyArray.push(photosData[j].originalFileKey);
                }
            }
        }
        mc.showPhotosByIndex(photoKeyArray, currIndex);
    };
    util.showAllPhotosByIndex = function (obj, currIndex) {
        var data = vars.ractiveAllDynamicList.data.ractiveData;
        common.showPhotosByIndex($(obj).parents(".photos-container").attr("value"), currIndex);
    };
    util.showRemarkPhotosByIndex = function (obj, currIndex) {
        common.showPhotosByIndex($(obj).parents(".photos-container").attr("value"), currIndex);
    };
    util.showReplyRemarkPhotosByIndex = function (obj, currIndex) {
        common.showReplyPhotosByIndex($(obj).parents(".photos-container").attr("value"), currIndex);
    };
    util.ajaxStarted = function (ajaxID) {
        var ajaxItem = $("#ajaxItem" + ajaxID);
        common.changeAjaxBadgeStatus(1, ajaxItem, "abnoralRemark", ajaxID);
        common.changePhotosProgress()
    };
    util.ajaxCompleted = function (ajaxID, result) {
        //alert(222)
        var ajaxItem = $("#ajaxItem" + ajaxID);
        ajaxItem.find(".imgprogress").hide().html("");
        //alert(result)
        if (result == "success") {
            common.changeAjaxBadgeStatus(2, ajaxItem, "abnoralRemark", ajaxID)
        } else if (result == "failed") {
            common.changeAjaxBadgeStatus(3, ajaxItem, "abnoralRemark", ajaxID);
        }
    };

})();